#include "list.h"

//int insert_to_list( struct list *list, struct plugin *plugin ) 
int insert_to_list( struct list *list, void *data ) 
{
	struct list_node *node = ( struct list_node *) malloc( sizeof( struct list_node ) );
	if ( node == NULL ) {
		fprintf( stderr, "List node allocation failed, out of memory. \n" );
		return -1;	
	}

	node->data = data;

	node->next = list->head;
	list->head = node;

	return 0;
}

int remove_from_list( struct list *list, struct list_node *f_node ) 
{
	struct list_node *node;
	struct list_node *prev_node = NULL;

	node = list->head;
	while ( node != NULL ) {
		if ( node == f_node ) 
			break;

		prev_node = node;
		node = node->next;
	}
	
	if ( node == NULL ) {
		fprintf( stderr, "Could not find node from list.\n" );
		return -1;
	}

	if ( prev_node != NULL ) 
		prev_node->next = node->next;
	else {
		list->head = node->next;
	}		

	free( node->data ); /* Is it list's task to free void *data pointer?*/
	free( node );

	return 0;
}

struct list * new_list() 
{
	struct list *list_t = ( struct list *) malloc( sizeof( struct list ) );

	if ( list_t == NULL ) {
		fprintf( stderr, "List allocation failed, out of memory. \n" );		
		return NULL;
	}

	list_t->head = NULL;

	return list_t;
}

void delete_list( struct list *list )
{
	if ( list != NULL ) {
		struct list_node *node;
		struct list_node *tmp;
		node = list->head;
		while ( node != NULL ) {
			tmp = node;
			node = node->next;
			free( tmp );
		}
		free( list );
	}
}
